package com.mingdao.lhy.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import com.linuxense.javadbf.DBFException;
import com.mingdao.lhy.biz.WishFillingBiz;
import com.mingdao.lhy.mapper.signup.SignUpStudentMapper2;
import com.mingdao.lhy.mapper.wish.ZkwMapper;
import com.mingdao.lhy.pojo.HighSchoolWish;
import com.mingdao.lhy.pojo.MiddleSchoolWish;
import com.mingdao.lhy.pojo.ResponseVo;
import com.mingdao.lhy.pojo.SignUpStudent;
import com.mingdao.lhy.pojo.Zkw;
import com.mingdao.lhy.pojo.page.ChangePassword;
import com.mingdao.lhy.pojo.signup.SignUpStudent2;
import com.mingdao.lhy.service.CityService;
import com.mingdao.lhy.service.HighSchoolServiceImpl;
import com.mingdao.lhy.service.StatEnrolService;
import com.mingdao.lhy.service.WishFillingService;
import com.mingdao.lhy.util.DbfUtils;

@Controller
@RequestMapping("/statenrol")
public class WishStatEnrol {

	private static Logger log = LoggerFactory.getLogger(HighSchoolServiceImpl.class);

	@Value("${dbfpath}")
	private String dbfPath;
	
	@Autowired
	private WishFillingBiz wishFillingBiz;

	@Autowired
	private ZkwMapper zkwMapper;

	@Autowired
	private CityService cityService;

	@Autowired
	private StatEnrolService statEnrolService;

	@Autowired
	private WishFillingService wishFillingService;
	
	@Autowired
	private SignUpStudentMapper2 signUpStudentMapper2;

	@RequestMapping("")
	public String index() {
		return "loginStatEnrol";
	}

	/**
	 * 州招办登录验证页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/check", method = RequestMethod.POST)
	public String check(@ModelAttribute("zkw") Zkw zkw, Model model) {

		HttpSession session = wishFillingBiz.getSession();

		log.debug("进入【州招办登录验证页面】");
		if (null == zkw || null == zkw.getUserid() || null == zkw.getPassword()) {
			log.error("没有收到有效的请求数据");
			model.addAttribute("msg", "没有收到有效的请求数据");
			return "loginStatEnrol";
		}
		/**
		 * 如果登录的用户ID不为空，并且不等于"71000002"，则不是州招办身份
		 */
		if (null != zkw.getUserid() && !"71000002".equals(zkw.getUserid())) {
			log.error("只能是州招办登录");
			model.addAttribute("msg", "只能是州招办登录");
			return "loginStatEnrol";
		}
		/**
		 * 根据州招办代码查询高中学校信息
		 */
		Zkw zkwDb = new Zkw();
		zkwDb = zkwMapper.getOne(zkw.getUserid());
		if (null == zkwDb) {
			log.error("没有找到州招办");
			model.addAttribute("msg", "没有找到指定的州招办");
			return "loginStatEnrol";
		}

		/**
		 * 判断州招办是否第一次登录（如果密码为空，或者和县市招办代码相同则是初次登录）
		 * 
		 * 如果是，跳转到修改密码界面，如果不是，则继续前进到操作选择页面
		 */
		String dbPassword = zkwDb.getPassword().trim();
		if (null == dbPassword || dbPassword.equals(zkwDb.getUserid())) {
			log.debug("州招办初次登录 ，进入【密码修改页面】");
			model.addAttribute("zkw", zkwDb);
			session.setAttribute("zkw", zkwDb);
			return "statenrol/changePasswdStatEnrol";

		}

		// 验证是否找到对应的州招办
		// 并且输入的密码是否和查找到的县市办密码是否一致
		if (null != zkwDb.getPassword() && zkwDb.getPassword().equals(zkw.getPassword())) {

			// 验证成功转到填报页面
			log.debug("验证【成功】");
			model.addAttribute("zkw", zkwDb);
			if (null == session) {
				session = wishFillingBiz.getSession();
			}
			session.setAttribute("zkw", zkwDb);

			// 转到选择页面
			return "statenrol/statEnroleselect";
		} else {
			// 验证失败继续回到登录页面
			// Model model = new Model();
			log.debug("验证【失败】");

			model.addAttribute("msg", "验证失败，代码或密码不正确");
			return "loginStatEnrol";
		}

	}

	@RequestMapping(value = "/doChangePasswd", method = RequestMethod.POST)
	public String changePwd(@ModelAttribute(value = "changePassword") ChangePassword changePassword,
			@SessionAttribute Zkw zkw, Model model) {

		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("州招办未登录，请重新登录");
			return "redirect:/loginStatEnrol";
		}
		// zkw = (Zkw) session.getAttribute("zkw");
		/**
		 * 判断传入的密码
		 */
		if (null == model || null == model.asMap() || null == model.asMap().get("changePassword")) {
			log.error("未取到前台返回的密码值 ");
			model.addAttribute("msg", "未取到前台返回的密码值");
			// model.addAttribute("student", student);
			return "statenrol/changePasswdStatEnrol";
		}

		ChangePassword cp = (ChangePassword) model.asMap().get("changePassword");
		if (null == cp.getOldPassword()) {
			log.error("必须输入原来的密码值 ");
			model.addAttribute("msg", "必须输入原来的密码值");
			return "/statenrol/check";
		}
		if (null == cp.getNewPasswordOne() || null == cp.getNewPasswordTwo()) {
			log.error("必须输入新的码值 ");
			model.addAttribute("msg", "必须输入新的码值");
			// model.addAttribute("student", student);
			return "/statenrol/changePasswdStatEnrol";
		}

		String oldPassword = cp.getOldPassword();
		String newPasswordOne = cp.getNewPasswordOne();
		String newPasswordTwo = cp.getNewPasswordTwo();

		/**
		 * 如果输入的旧密码等于学生本来的旧密码才可以更换密码
		 */
		if (!oldPassword.isEmpty() && !zkw.getPassword().isEmpty()) {
			if (oldPassword.equals(zkw.getPassword())) {
				/**
				 * 两次输入密码要一致才有效
				 */
				if (newPasswordOne.equals(newPasswordTwo)) {
					zkw.setPassword(newPasswordOne);
				} else {
					log.error("两次密码不符，请重新核对 ");
					model.addAttribute("msg", "两次密码不符，请重新核对 ");
					model.addAttribute("zkw", zkw);
					return "/statenrol/changePasswdStatEnrol";
				}
			} else {
				log.error("原密码不符，请重新核对 ");
				model.addAttribute("msg", "原密码不符，请重新核对 ");
				model.addAttribute("zkw", zkw);
				return "/statenrol/changePasswdStatEnrol";
			}
		}
		/**
		 * 修改密码
		 */
		int result = cityService.changePassword(zkw);
		if (1 == result) {
			log.debug("密码修改成功");
		} else {
			log.warn("密码修改失败");
			model.addAttribute("zkw", zkw);
			return "/statenrol/changePasswdStatEnrol";
		}
		/**
		 * 跳转到登录界面重新登录
		 */
		return "loginStatEnrol";
	}

	@RequestMapping("showHighSchoolInit")
	public String highSchoolWishInit(Model model) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("未登录，请重新登录");
			/* return "redirect:/loginStatEnrol"; */
		}
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		model.addAttribute("zkw", zkw);
		return "statenrol/statEnrolHigh";

	}

	@RequestMapping("showHighSchool")
	@ResponseBody
	public Map<String, Object> highSchoolWish(@RequestParam String bmh, Model model, @RequestParam int pageSize,
			@RequestParam int pageIndex) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("未登录，请重新登录");
			/* return "redirect:/loginStatEnrol"; */
		}
		List<HighSchoolWish> students;
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		model.addAttribute("zkw", zkw);
		if (null == bmh || bmh.isEmpty()) {
			students = statEnrolService.getWishedStudentPage(pageSize, pageIndex);

		} else {
			students = statEnrolService.statEnrolgetOne(bmh);
		}
		model.addAttribute("students", students);
		String total = students.get(0).getTotal().toString();
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", Integer.parseInt(total));
		result.put("rows", students);
		return result;

		/* model.addAttribute("page", result); */

		/* return "statenrol/statEnrolHigh"; */
	}

	@RequestMapping("showMiddleSchoolInit")
	public String middleShoolWishInit(Model model) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			return "redirect:/loginStatEnrol";
		}
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		model.addAttribute("zkw", zkw);
		return "statenrol/StatEnrolMid";
	}

	@RequestMapping("showMiddleSchool")
	@ResponseBody
	public Map<String, Object> middleShoolWish(@RequestParam String bmh, Model model, @RequestParam int pageSize,
			@RequestParam int pageIndex) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("zkw")) {
			session = null;
			log.error("未登录，请重新登录");
			/* return "redirect:/loginStatEnrol"; */
		}
		List<MiddleSchoolWish> students;
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		model.addAttribute("zkw", zkw);
		if (null == bmh || bmh.isEmpty()) {
			students = statEnrolService.getMidWishedStudentPage(pageSize, pageIndex);

		} else {
			students = statEnrolService.statEnrolgetMidOne(bmh);
		}
		model.addAttribute("students", students);
		String total = students.get(0).getTotal().toString();
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", Integer.parseInt(total));
		result.put("rows", students);
		return result;

	}

	@RequestMapping("doSelectStudentWishByBmh")
	@ResponseBody
	public Map<String, Object> selectStudentWishByBmh(@ModelAttribute("bmh") String bmh,
			@ModelAttribute("sele") String sele, Model model) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		String total = "";
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("招办未登录，请重新登录");
			/* return "redirect:/loginStatEnrol"; */
		}

		if (null == sele || sele.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件学生填报类别");
			vo.setUrl("statenrol/statEnrolHigh");
			// return vo;
		}

		/*
		 * if (null == bmh || bmh.isEmpty()) { vo.setCode("stay");
		 * vo.setMessage("未收到查询条件报名号"); vo.setUrl("statenrol/statEnrolHigh"); return vo;
		 * }
		 */
		/* HighSchoolWish students = statEnrolService.getOne(bmh); */

		/* model.addAttribute("students", students); */
		model.addAttribute("zkw", zkw);
		model.addAttribute("sele", sele);

		// vo.setCode("ok");
		// vo.setMessage("查询完成");
		vo.setUrl("/statenrol/statEnrolHigh");
		/* model.addAttribute("students", students); */
		/* total=students.getTotal().toString(); */
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", 1);
		/* result.put("rows",students); */
		return result;

	}

	@RequestMapping("edoSelectStudentWishByCondition")
	public String selectStudentWishByCondition(@ModelAttribute("sele") String sele, Model model) {
		HttpSession session = wishFillingBiz.getSession();
		ResponseVo vo = new ResponseVo();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("县市招办未登录，请重新登录");
			vo.setUrl("redirect:/loginStatEnrol");
			// return vo;
		}
		if (null == sele || sele.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件学生填报类别");
			vo.setUrl("statenrol/statEnrolHigh");
			// return vo;

		}

		List<SignUpStudent> students = new ArrayList<SignUpStudent>();
		/**
		 * 未填志愿
		 */
		if ("1".equals(sele)) {
			students = cityService.getWishedStudentByXsdmNotWished(zkw.getXsdm(), null);
		} else if ("0".equals(sele)) {
			/**
			 * 已填志愿
			 */
			students = cityService.getWishedStudentByXsdmWished(zkw.getXsdm(), null);
		}

		model.addAttribute("students", students);
		model.addAttribute("zkw", zkw);
		model.addAttribute("sele", sele);

		// return vo;
		return "/statenrol/statEnrolHigh";
	}

	@RequestMapping("edoSelectStudentWishByBmhMiddle")
	public String selectStudentWishByBmhMiddle(@ModelAttribute("bmh") String bmh, @ModelAttribute("sele") String sele,
			Model model) {
		ResponseVo vo = new ResponseVo();
		HttpSession session = wishFillingBiz.getSession();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("县市招办未登录，请重新登录");
			vo.setUrl("redirect:/loginStatEnrol");
			// return vo;
		}

		if (null == sele || sele.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件学生填报类别");
			vo.setUrl("statenrol/statEnrolMid");
			// return vo;
		}

		if (null == bmh || bmh.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件报名号");
			vo.setUrl("statenrol/statEnrolMid");
			// return vo;
		}
		List<SignUpStudent> students = new ArrayList<SignUpStudent>();
		/**
		 * 未填志愿
		 */
		if ("1".equals(sele)) {
			students = cityService.getWishedStudentByXsdmNotWishedMiddle(zkw.getXsdm(), bmh);
		} else if ("0".equals(sele)) {
			/**
			 * 已填志愿
			 */
			students = cityService.getWishedStudentByXsdmWishedMiddle(zkw.getXsdm(), bmh);
		}

		model.addAttribute("students", students);
		model.addAttribute("zkw", zkw);
		model.addAttribute("sele", sele);

		// vo.setCode("ok");
		// vo.setMessage("查询完成");
		vo.setUrl("statenrol/statEnrolMid");

		return "statenrol/statEnrolMid";
	}

	@RequestMapping("edoSelectStudentWishByConditionMiddle")
	public String selectStudentWishByConditionMiddle(@ModelAttribute("sele") String sele, Model model) {
		HttpSession session = wishFillingBiz.getSession();
		ResponseVo vo = new ResponseVo();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("县市招办未登录，请重新登录");
			vo.setCode("error");
			vo.setMessage("县市招办未登录，请重新登录");
			vo.setUrl("redirect:/loginCity");
			// return vo;
		}
		if (null == sele || sele.isEmpty()) {
			vo.setCode("stay");
			vo.setMessage("未收到查询条件学生填报类别");
			vo.setUrl("/statenrol/statEnrolMid");
			// return vo;

		}

		List<SignUpStudent> students = new ArrayList<SignUpStudent>();
		/**
		 * 未填志愿
		 */
		if ("1".equals(sele)) {
			students = cityService.getWishedStudentByXsdmNotWishedMiddle(zkw.getXsdm(), null);
		} else if ("0".equals(sele)) {
			/**
			 * 已填志愿
			 */
			students = cityService.getWishedStudentByXsdmWishedMiddle(zkw.getXsdm(), null);
		}

		model.addAttribute("students", students);
		model.addAttribute("zkw", zkw);
		model.addAttribute("sele", sele);

		// return vo;
		return "statenrol/statEnrolMid";
	}

	@RequestMapping("forgetPwd")
	public String forgetPwd() {
		return "city/CountyEnrolStudent";
	}
	
	/**
	 * 导出已报名学生DBF文件
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "exportSignUpStudent")
	@ResponseBody
	public String exportSignUpStudent(HttpServletResponse response, Model model) {
		HttpSession session = wishFillingBiz.getSession();
		Zkw zkw = (Zkw) session.getAttribute("zkw");
		if (null == session || null == zkw) {
			session = null;
			log.error("用户未登录，请重新登录");
			return "loginStatEnrol";
		}

		List<SignUpStudent2> students = signUpStudentMapper2.listAllBmk();
		DbfUtils dbf = new DbfUtils();
		String savePath = dbfPath;
		try {

			if (savePath.endsWith("/")) {
				if (!savePath.endsWith(zkw.getUserid() + "/")) {
					savePath = savePath + zkw.getUserid() + "/";
				}

			} else {
				if (!savePath.endsWith(zkw.getUserid())) {
					savePath = savePath + "/" + zkw.getUserid() + "/";
				}
			}

			// 判断目录是否存在
			File dir = new File(savePath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			String filePath = savePath + "ls18bmk.dbf";

			dbf.writeSignUpStudent(students, filePath);

			String path = filePath;
			response.reset();
//			path = URLEncoder.encode(path,"UTF-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + filePath.substring(filePath.lastIndexOf("/") + 1));
			OutputStream ous = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream;charset=utf-8");
			File file = new File(path);
			response.addHeader("Content-Length", "" + file.length());

			try {
				FileInputStream inputStream = new FileInputStream(file);
				int b = 0;
				byte[] buffer = new byte[512];
				do {
					b = inputStream.read(buffer);
					if (b < 0) {
						break;
					}
					ous.write(buffer, 0, b);
				} while (true);
				inputStream.close();
				ous.flush();
				ous.close();

			} catch (IOException e) {
				e.printStackTrace();
			}

		} catch (DBFException | IOException e) {
			e.printStackTrace();
		}

		return "statenrol/statEnroleselect";
	}
	
	/**
	 * 
	 * @param response
	 */
	public void downloadDbf(HttpServletResponse response, String dbfName) {
		// 得到ClassLoader 先得到Class,在得到ClassLoader
		//ClassLoader c1 = this.getClass().getClassLoader();
		// 调用其getResourceAsStream，得到一个InputStream
		//URL url = c1.getResource(dbfName);
		// String path = url.getPath();
		String path = dbfName;

		response.reset();
		// 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
		// response.setContentType("multipart/form-data");
		response.setContentType("application/octet-stream;charset=UTF-8");
		// 2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
//		response.setHeader("Content-Disposition",
//				"attachment;fileName=" + dbfName.substring(dbfName.lastIndexOf("/") + 1));
		response.setHeader("Content-Disposition",
				"attachment;filename*=UTF-8''" + dbfName.substring(dbfName.lastIndexOf("/") + 1));
		ServletOutputStream out;
		// 通过文件路径获得File对象(假如此路径中有一个download.pdf文件)
		File file = new File(path);

		try {
			FileInputStream inputStream = new FileInputStream(file);

			// 3.通过response获取ServletOutputStream对象(out)
			out = response.getOutputStream();

			int b = 0;
			byte[] buffer = new byte[512];
			while (b != -1) {
				b = inputStream.read(buffer);
				// 4.写到输出流(out)中
				out.write(buffer, 0, b);
			}
			inputStream.close();
			out.flush();
			out.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
